import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as vscode from 'vscode';
import * as configuration from '../configuration';
import { log } from '../helper/outputChannel';
import { Helper } from '../helper';
import { TornaDocDetail } from '../types/type';

export async function selectTemplateFile() {
  const workspace = await Helper.workspace().catch(e => { vscode.window.showErrorMessage(e); });
  if (!workspace) { return; }

  log.show();
  log.info('selectTemplateFile() 选择选择接口代码模板文件...');
  const uris = await vscode.window.showOpenDialog({
    canSelectFiles: true,
    canSelectFolders: false,
    canSelectMany: false,
    title: "选择接口代码模板文件",
    filters: {
      // eslint-disable-next-line @typescript-eslint/naming-convention
      // TypeScript: ['ts']
    },
    defaultUri: workspace.uri,
  });
  if (!uris?.length) {
    log.info('selectTemplateFile() 已取消');
    return;
  }

  const ret = Helper.fsPath(uris[0]).replace(Helper.fsPath(workspace.uri) + '/', '');
  configuration.setDefaultTemplatePath(ret);
  return ret;
}

export async function ensureTemplateFile(doc?: TornaDocDetail): Promise<string> {

  const p = configuration.getTemplatePath(doc) || await selectTemplateFile();
  if (!p) { throw new Error('未选择代码模板文件'); }

  const workspace = await Helper.workspace();
  const stat = await fs.stat(path.join(Helper.fsPath(workspace.uri), p));
  if (!stat.isFile()) {
    throw new Error(`该路径不是文件！${p}`);
  }
  return p;
}